package cumeo89.chii.client.ui;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;

import cumeo89.chii.client.util.Action;
import cumeo89.chii.client.util.MyChangeListener;

public class ImageMenuItem extends MenuItem implements MyChangeListener {

	private AbstractImagePrototype imagePrototype;
	private Action action = null;
	private boolean enabled = true;

	public ImageMenuItem(AbstractImagePrototype imagePrototype, String text,
			MenuBar subMenu) {
		this(imagePrototype, text, false, subMenu);
	}

	public ImageMenuItem(AbstractImagePrototype imagePrototype, String text,
			boolean asHTML, MenuBar subMenu) {
		super(text, asHTML, subMenu);
		setImagePrototype(imagePrototype);
	}

	public ImageMenuItem(AbstractImagePrototype imagePrototype, String text,
			Action action) {
		this(imagePrototype, text, false, action);
	}

	public ImageMenuItem(AbstractImagePrototype imagePrototype, String text,
			boolean asHTML, Action action) {
		super(text, asHTML, action);
		setAction(action);
		setImagePrototype(imagePrototype);
	}

	private void setAction(Action action) {
		if (this.action != null) {
			this.action.removeChangeListener(this);
		}
		this.action = action;
		if (action != null) {
			action.addChangeListener(this);
		}
		setEnabled(action.isEnabled());
	}

	public AbstractImagePrototype getImagePrototype() {
		return imagePrototype;
	}

	public void setImagePrototype(AbstractImagePrototype imagePrototype) {
		this.imagePrototype = imagePrototype;
		updateImage();
	}

	private void updateImage() {
		if (imagePrototype != null) {
			DOM.setInnerHTML(getElement(), imagePrototype.getHTML() + "&nbsp;"
					+ DOM.getInnerHTML(getElement()));
		}
	}

	@Override
	public void setHTML(String html) {
		super.setHTML(html);
		updateImage();
	}

	@Override
	public void setText(String text) {
		super.setText(text);
		updateImage();
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		if (this.enabled != enabled) {
			this.enabled = enabled;
			if (action != null) {
				action.setEnabled(enabled);
			}
		}
	}

	@Override
	public Command getCommand() {
		return enabled ? super.getCommand() : null;
	}

	public void onChanged(Object sender) {
		if (sender == action) {
			setEnabled(action.isEnabled());
		}
	}

}
